package com.mujiutian.wx.controller;

import cn.hutool.http.HttpUtil;
import com.mujiutian.wx.entity.WxBean;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;


@Controller
@RequestMapping(value = "/wx")
@Slf4j
public class WxController {

    private WxBean wxBean = new WxBean();

    @GetMapping(value = "/getWxCode.html")
    public String getWxCode() throws UnsupportedEncodingException {

        // 1、redirect_uri设置
        String redict = URLEncoder.encode("http://9fvs5p.natappfree.cc/wx/getWxAccessToken.html", "UTF-8");

        // 2、获取code的url
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+wxBean.getAppId()+"&redirect_uri="+redict+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";

        // 3、重定向去微信获取code，之后去回掉接口/getWxAccessToken.html
        return "redirect:" + url;
    }

    @GetMapping(value = "/getWxAccessToken.html")
    public String getWxAccessToken(HttpServletRequest request){

        // 1、获取code
        String code = request.getParameter("code");

        // 2、拼接获取access_token的url
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+wxBean.getAppId()+"&secret="+wxBean.getAppSecret()+"&code="+code+"&grant_type=authorization_code";

        // 3、调用获取access_token
        String result = HttpUtil.get(url);

        // 4、转换结果
        JSONObject jsonObject = JSONObject.fromObject(result);
        if (null == jsonObject || jsonObject.isEmpty() || jsonObject.get("access_token") == null || jsonObject.get("openid") == null) {
            return "/false";
        }

        // 5、取access_token
        String accessToken = jsonObject.get("access_token").toString();

        // 6、取openid
        String openId  = jsonObject.get("openid").toString();

        log.info("accessToken====="+accessToken);
        log.info("openId====="+openId);

        return "index";
    }

    @GetMapping("testToken.html")
    public void getToken(String signature, String timestamp, String nonce, String echostr, HttpServletResponse response) throws NoSuchAlgorithmException, IOException {
        // 将token、timestamp、nonce三个参数进行字典序排序
        log.info("signature:"+signature);
        log.info("timestamp:"+timestamp);
        log.info("nonce:"+nonce);
        log.info("echostr:"+echostr);
        log.info("TOKEN:"+"mdxlcj");
        String[] params = new String[] { "mdxlcj", timestamp, nonce };
        Arrays.sort(params);
        // 将三个参数字符串拼接成一个字符串进行sha1加密
        String clearText = params[0] + params[1] + params[2];
        String algorithm = "SHA-1";
        String sign = new String(org.apache.commons.codec.binary.Hex.encodeHex(MessageDigest.getInstance(algorithm).digest((clearText).getBytes())));
        // 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
        if (signature.equals(sign)) {
            response.getWriter().print(echostr);
        }
    }
}
